package wsi.exp.exp3.compare;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.rygh.core.algorithm.OrderedPrecisionRecall;

import wsi.exp.exp3.GoldSetMatch;
import wsi.exp.exp3.PathMatchPair;
import wsi.function.Function;

public class Exp3PredComparator extends Exp3Comparator {

	private final Set<String> hitPredSet = new HashSet<>();

	public Exp3PredComparator(Function function, int threshold) {
		super(function, threshold);
	}

	@Override
	public void calibrate() {
		PathMatchPair hit;
		Set<String> totalPredSet = new HashSet<>();
		List<PathMatchPair> pairs = new ArrayList<>();

		for (PathMatchPair pair : matchResult.getPairs()) {

			// if (pair.getPredicatePath().isTemp())
			// continue;

			// prevent 0.70 < 0.70, don't know why this is true for java.
			if (pair.getConfidence() + .000001 < .01 * threshold) {
				// System.out.printf("calibrate %s: %f < %f\n", e.getKey(),
				// counter.get(key).getPrecision(), threshold);
				continue;
			}

			pairs.add(pair);
			totalPredSet.add(pair.getPredicatePath().getKey());
		}

		sortPairs(pairs);

		for (PathMatchPair pair : pairs) {
			if (totalPredSet.isEmpty())
				break;

			hit = goldSet.find(pair);

			if (hit != null) {
				String key = pair.getPredicatePath().getKey();

				if (!hitPredSet.contains(key))
					recall.retrieve(true);

				hitPredSet.add(key);
				totalPredSet.remove(key);
			} else
				recall.retrieve(false);
		}
	}

	@Override
	protected boolean checkHit(PathMatchPair pair, boolean gold) {
		return hitPredSet.contains(pair.getPredicatePath().getKey());
	}

	@Override
	public void setGoldSet(GoldSetMatch goldSet) {
		super.setGoldSet(goldSet);
		recall = new OrderedPrecisionRecall(goldSet.getGoldSizeByPred());
	}

}
